package
{
	import com.adobe.serialization.json.JSON;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.net.SharedObject;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.URLVariables;

	public class PersistanceLoader extends EventDispatcher
	{
		private var m_persistable:IPersistable;
		private var m_sharedObject:SharedObject;
		private var saveData:Array = [];
		private var saveProcessing:Boolean = false;
		
		public function PersistanceLoader(persistable:IPersistable)
		{
			m_persistable = persistable;
		}
		
		public function save():void{
			return;
			var data:String = JSON.encode(m_persistable.getSaveObject());
			saveData.unshift(data);
			if(!saveProcessing){
				saveProcessing = true;
				processNextSave();
			}
		}
		
		public function load():void{
			var url:String = 'http://vinhtrinh.org/labs/mallsim_server/gateway.php';
			var urlLoader:URLLoader = new URLLoader();
			var urlRequest:URLRequest = new URLRequest(url);
			urlRequest.method = URLRequestMethod.GET;
			urlRequest.data = new URLVariables();
			urlRequest.data['action'] = 'read';
			urlRequest.data['userId'] = Game.fbid;
			
			urlLoader.load(urlRequest);
			urlLoader.addEventListener(Event.COMPLETE, onRemoteLoadComplete);
		}		
		
		private function onRemoteLoadComplete(e:Event):void{
			var data:String = (e.currentTarget as URLLoader).data;
			var savedObject:Object;
			try{
				savedObject = JSON.decode(data);
			} catch(e:Error){
				trace("ERROR LOADING FROM REMOTE");
				var so:SharedObject = getLocalSharedObject();
				data = so.data.saveData;
				if(!data){
					Game.instance.loadStartingTestGame();
				} else {
					savedObject = JSON.decode(data);	
				}
				
			}
			
			if(false && savedObject){
				m_persistable.loadSavedObject(savedObject);
			} else {
				Game.instance.loadStartingTestGame();
			}
			dispatchEvent(new Event(Event.COMPLETE));
		}		
		
		public function canLoad():Boolean{
			var so:SharedObject = getLocalSharedObject();
			return (so.data.saveData != null);
		}
		
		private function processNextSave():void{
			var data:String = saveData.pop();
			saveLocal(data);
			saveRemote(data);
			
			if(saveData.length){
				processNextSave();
			} else {
				saveProcessing = false;
			}						
		}
		
		private function onRemoteSaveComplete(e:Event):void{
//			if((e.currentTarget as URLLoader).data != "ok"){
//				throw new Error("save object ordering error on server");
//			} else {
//				if(saveData.length){
//					processNextSave();
//				} else {
//					saveProcessing = false;
//				}
//			}		
		}
		
		private function getLocalSharedObject():SharedObject{
			if(!m_sharedObject){
				m_sharedObject = SharedObject.getLocal('save');
			}
			
			return m_sharedObject;
		}
		
		
		private function saveLocal(data:String):void{
			var so:SharedObject = getLocalSharedObject();
			so.data.saveData = data;
		}	
		
		
		
		private function saveRemote(data:String):void{
			var url:String = 'http://vinhtrinh.org/labs/mallsim_server/gateway.php';
			var urlLoader:URLLoader = new URLLoader();
			var urlRequest:URLRequest = new URLRequest(url);
			urlRequest.method = URLRequestMethod.POST;
			urlRequest.data = new URLVariables();
			urlRequest.data['action'] = 'write';
			urlRequest.data['userId'] = Game.fbid;
			urlRequest.data['gameBlob'] = data;
			
			urlLoader.load(urlRequest);
			urlLoader.addEventListener(Event.COMPLETE, onRemoteSaveComplete);			
		}
		
	}
}